<template>
  <div class="com-container">
    <div class="com-chart" ref="cost_ref"></div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      intervalId: null, //用于存储计时器ID
      chartInstance: null,
      allData: null,
      colorList: {
        linearYtoG: {
          type: 'linear',
          x: 0,
          y: 0,
          x2: 1,
          y2: 1,
          colorStops: [
            { offset: 0, color: 'yellowgreen' },
            { offset: 1, color: '#f5b44d' }
          ]
        },
        linearBtoG: {
          type: 'linear',
          x: 0,
          y: 0,
          x2: 1,
          y2: 0,
          colorStops: [
            { offset: 0, color: '#1c98e8' },
            { offset: 1, color: '#28f8de' }
          ]
        },
        areaBtoG: {
          type: 'linear',
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [
            { offset: 0, color: 'rgba(35,184,210,.2)' },
            { offset: 1, color: 'rgba(35,184,210,0)' }
          ]
        }
      }
    }
  },
  mounted() {
    this.initChart()
    this.getData()
    this.intervalId = setInterval(this.getData, 10000)
  },
  beforeDestroy() {
    // 在组件销毁之前清除计时器
    if (this.intervalId) {
      clearInterval(this.intervalId)
    }
  },
  methods: {
    initChart() {
      this.chartInstance = this.$echarts.init(this.$refs.cost_ref)
      const initOption = {
        tooltip: {
          trigger: 'axis', //触发提示
          backgroundColor: 'rgba(255,255,255,0.1)',
          axisPointer: {
            type: 'shadow',
            label: {
              show: true,
              backgroundColor: '#1c98e8'
            }
          }
        },
        legend: {
          data: ['预算', '成本'],
          textStyle: {
            color: '#B4B4B4'
          },
          top: '0%'
        }
      }
      this.chartInstance.setOption(initOption)
    },
    async getData() {
      const ret = await this.$http.post('http://localhost:9999/production_line/api/cost/all', {})
      // console.log(ret.data)
      // 按时间排序，从旧到新
      const sortedData = ret.data.sort((a, b) => new Date(a.safetyTime) - new Date(b.safetyTime))
      // 取最近的12个数据（保证最新的在最后一个）
      const recent12Data = sortedData.slice(-12)
      this.allData = recent12Data
      this.updateChart()
    },
    updateChart() {
      const months = this.allData.map(item => {
        const date = new Date(item.time)
        const year = date
          .getFullYear()
          .toString()
          .slice(2) // 获取年份后两位
        const month = (date.getMonth() + 1).toString().padStart(2, '0') // 获取月份并确保两位数
        return `${year}.${month}`
      })
      const machinebudget = this.allData.map(item => item.index)
      const machinecost = this.allData.map(item => item.fee)
      // this.allData.forEach(item => {
      //   const {
      //     name,
      //     value: { budget, cost }
      //   } = item
      //   months.push(name)
      //   machinebudget.push(budget)
      //   machinecost.push(cost)
      // })
      // console.log(months, machinebudget, machinecost)
      const dataOption = {
        xAxis: {
          type: 'category',
          axisLine: {
            lineStyle: {
              color: '#B4B4B4'
            }
          },
          axisTick: {
            show: false
          },
          // axisLabel: {
          //   rotate: 45, // 将标签旋转45度
          //   interval: 0 // 强制显示所有标签
          // },
          data: months
        },
        yAxis: {
          type: 'value',
          splitLine: {
            show: false
          },
          axisLine: {
            lineStyle: {
              color: '#B4B4B4'
            }
          },
          axisTick: {
            show: false
          },
          axisLabel: {
            formatter: '{value} '
          }
        },
        series: [
          {
            name: '成本',
            type: 'line',
            smooth: true,
            symbol: 'emptyCircle',
            symbolSize: 8,
            itemStyle: {
              normal: {
                color: '#28f8de'
              }
            },
            lineStyle: {
              normal: {
                color: this.colorList.linearBtoG,
                width: 3
              }
            },
            areaStyle: {
              normal: {
                color: this.colorList.areaBtoG
              }
            },
            lineSmooth: true,
            data: machinecost
          },
          {
            name: '预算',
            type: 'line',
            smooth: true,
            symbol: 'emptyCircle',
            symbolSize: 8,
            itemStyle: {
              normal: {
                color: '#f5b44d'
              }
            },
            lineStyle: {
              normal: {
                color: this.colorList.linearYtoG,
                width: 3
              }
            },
            lineSmooth: true,
            z: -1,
            data: machinebudget
          }
        ]
      }
      this.chartInstance.setOption(dataOption)
    }
  }
}
</script>

<style></style>
